import {Component, OnInit,} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {Fieldconf} from "../fieldconf";
import {MsgConstants} from "../../../../constants/constants";
import {MsgResult} from "../../../../models/msg-result";
import {DsService} from "../../ds/ds.service";
import {Dsconf} from "../dsconf";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {DsconfService} from "../dsconf.service";


declare var $;

var log, className = "dark";

var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

var nameNumber = 1;
var factorNumber = 1;
var attributeNumber = 1;
var metaAttributeNumber = 1;

@Component({
  selector: 'app-fieldconf-add',
  templateUrl: './fieldconf-add.component.html',
  styleUrls: ['./fieldconf-add.component.css']
})
export class FieldconfAddComponent implements OnInit {

  treeObj;

  expand: boolean = true;

  saveCopyNodes = [];

  name: string = 'name';

  attribute: string = 'attr'

  metaAttribute: string = 'metaAttr'

  factor: string = 'factor';

  dsConfNames: Array<any> = [];

  fieldConfId: string;

  selectedNode = [];

  dsConf: Dsconf;

  fieldConfForm: FormGroup;

  fieldConf: Fieldconf;


  fieldConfs: Array<any> = [];

  oriDsNames: Array<any> = [];

  oriTables: Array<any> = [];

  auditDsIdNames: Array<any> = [];

  auditTables: Array<any> = [];

  formErrors = {
    'oriDsId': '',
    'oriTable': '',
    'auditDsId': '',
    'auditDsName': '',
    'auditTable': '',

  };
  private validationMessages = {
    'oriDsId': {
      'required': '原始数据源不能为空'
    },
    'auditDsName': {
      'required': '数据审核不能为空',
      'pattern': '请输入汉字字母或数字',
      'maxlength':'长度不能超过20'
    },
    'oriTable': {
      'required': '原始表不能为空',
      'pattern': '请输入字母,数字，"-"或"_"',
      'maxlength':'长度不能超过30'
    },
    'auditDsId': {
      'required': '存储数据源不能为空'
    },
    'auditTable': {
      'required': '存储数据表不能为空',
      'pattern': '请输入字母,数字，"-"或"_"',
      'maxlength':'长度不能超过30'
    },
  };


  setting = {
    edit: {
      enable: true,
      showRemoveBtn: this.showRemoveBtn,
      showRenameBtn: this.showRenameBtn,
      removeTitle: '移除节点',
      renameTitle: '修改名称',
      editNameSelectAll: true,
    },
    data: {
      simpleData: {
        enable: true,
      }
    },
    view: {
      addHoverDom: (treeId, treeNode) => {
        return this.addHoverDom(treeId, treeNode)
      },
      removeHoverDom: this.removeHoverDom,
      addDiyDom: (treeId, treeNode) => {
        return this.addDiyDom(treeId, treeNode)
      },
    },
    callback: {
      beforeRename:this.beforeRename,
    },
  };

  zNodes = [
    {
      id: this.getUUID(), pId: null, nodeType: 1, name: "root", open: true, icon: 'assets/v1/css/audit/imgs/R.svg',
      children: [{
        id: this.getUUID(), nodeType: 1, name: "site", open: true, icon: 'assets/v1/css/audit/imgs/F.svg',
        children: [
          {
            id: this.getUUID(), nodeType: 2, name: "siteName", open: true, icon: 'assets/v1/css/audit/imgs/A.svg',
            children: [
              {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
            ]
          },
          {
            id: this.getUUID(), nodeType: 2, name: "siteCode",  icon: 'assets/v1/css/audit/imgs/A.svg',
            children: [
              {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
            ]
          },
        ]
      },
        {
          id: this.getUUID(), nodeType: 1, name: "device", open: true, icon: 'assets/v1/css/audit/imgs/F.svg',
          children: [
            {
              id: this.getUUID(), nodeType: 2, name: "deviceName", icon: 'assets/v1/css/audit/imgs/A.svg',

              children: [
                {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
              ]
            },
            {
              id: this.getUUID(), nodeType: 2, name: "deviceCode", icon: 'assets/v1/css/audit/imgs/A.svg',

              children: [
                {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
                {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
              ]
            },
          ]
        },
        {
          id: this.getUUID(), name: "factors", nodeType: 1, open: true, icon: 'assets/v1/css/audit/imgs/L.svg',
          children: [
            {
              id: this.getUUID(), name: "factor", nodeType: 1, open: true, icon: 'assets/v1/css/audit/imgs/F.svg',
              children: [
                {
                  id: this.getUUID(), nodeType: 2, name: "code", icon: 'assets/v1/css/audit/imgs/A.svg',
                  children: [
                    {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
                  ]
                },
                {
                  id: this.getUUID(), nodeType: 2, name: "name", icon: 'assets/v1/css/audit/imgs/A.svg',
                  children: [
                    {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
                  ]
                },
                {
                  id: this.getUUID(), nodeType: 2, name: "value", icon: 'assets/v1/css/audit/imgs/A.svg',
                  children: [
                    {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
                    {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
                  ]
                },
              ]
            },
          ]
        },]
    },

  ];

  constructor(private router: Router,
              private route: ActivatedRoute,
              private fb: FormBuilder,
              private responseUtil: ResponseUtil,
              private pageSubject: PageSubject,
              private dialogService: OneDialogService,
              private dsService: DsService,
              private dsConfService: DsconfService,) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    // if (!!this.route.snapshot.params['fieldConfId']) {
    //   this.fieldConfId = this.route.snapshot.params['fieldConfId'];
    //   this.initFieldConfUpdateTree(this.fieldConfId);
    // }
    this.initFieldConfTree();
    this.initDsConfNameAndTable();
  }


  private pushPage() {
    const path = new Path('审核系统', '');
    this.pageSubject.pushPage('字段配置', '新增', path);
  }

  /**
   * 构造表单
   */
  buildForm(): void {
    this.fieldConfForm = this.fb.group({
      'oriDsId': [this.dsConf.oriDsId, [
        Validators.required,
      ]],
      'oriTable': [this.dsConf.oriTable, [
        Validators.required,
        Validators.pattern(/^[A-Za-z0-9_-]+$/),
        Validators.maxLength(30)

      ]],
      'isKeepOri': ['0'],
      'auditDsName': [this.dsConf.auditDsName, [
        Validators.required,
        Validators.pattern(/^[\u4e00-\u9fa50-9A-Za-z]+$/),
        Validators.maxLength(20)
      ]],
      'auditDsId': [this.dsConf.auditDsId, [
        Validators.required
      ]],
      'auditTable': [this.dsConf.auditTable, [
        Validators.required,
        Validators.pattern(/^[A-Za-z0-9_-]+$/),
        Validators.maxLength(30)
      ]],
      'isUse':  ['1']
    });

    this.fieldConfForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.fieldConfForm) {
      return;
    }
    const form = this.fieldConfForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 初始化树
   */
  private initFieldConfTree() {
    this.treeObj = $.fn.zTree.init($("#field_add_fieldConfTree"), this.setting, this.zNodes);
    this.treeObj.expandNode(this.zNodes, true, true, true);
    this.treeObj.expandAll(true);
  }


  /**
   * DIYTree向树中添加input输入框
   * @param treeId
   * @param treeNode
   */
  private addDiyDom = (treeId, treeNode) => {
    // if (treeNode.parentNode && treeNode.parentNode.nodeType != ) return;
    var aObj = $("#" + treeNode.tId + "_a");
    if (treeNode.valuePath == null) {
      treeNode.valuePath = '';
    }
    if (treeNode.defaultValue == null) {
      treeNode.defaultValue = '';
    }
    if (treeNode.nodeType == 3) {
      /**
       * height: 30px;
       padding: 2px;
       line-height: 30px;
       margin: 0 5px 5px 3px;
       * @type {string}
       */
      if (treeNode.name == 'type') {
        var valuePath = "<input class='form-control'  value='" + treeNode.valuePath + "' "+
          "placeholder='路径:$.pollutant[0].Mark' id='diyIntPath_" + treeNode.id + "'>";
        aObj.after(valuePath);
        var defaultValue = "<select class='form-control'  value='" + treeNode.defaultValue + "' id='diyIntDef_" + treeNode.id + "'>" +
          "<option  value= 1 >字符串</option>" +
          "<option  value= 2 >整数</option>" +
          "<option  value= 3 >小数</option>" +
          "<option  value= 4 >日期</option> </select>";
        aObj.after(defaultValue);
        var btn = $("#diyIntPath_" + treeNode.id);
        var btn1 = $("#diyIntDef_" + treeNode.id);
        if (btn) btn.bind("blur", function () {
          treeNode.valuePath = btn.val();
        });
        if(treeNode.defaultValue == "") {
          treeNode.defaultValue = 1;
        }else{
          btn1.value = treeNode.defaultValue;
        }
        if (btn1) btn1.bind("click", function () {
          treeNode.defaultValue = btn1.val();
        });
      } else if (treeNode.name == 'isVisiable') {
        var valuePath = "<input class='form-control'  value='" + treeNode.valuePath + "' "+
          "placeholder='路径:$.pollutant[0].Mark' id='diyIntPath_" + treeNode.id + "'>";
        aObj.after(valuePath);
        var defaultValue = "<select class='form-control'  value='" + treeNode.defaultValue + "' id='diyIntDef_" + treeNode.id + "'>" +
          "<option  value= 0 >否</option>" +
          "<option  value= 1 >是</option>" +
          " </select>";
        aObj.after(defaultValue);
        var btn = $("#diyIntPath_" + treeNode.id);
        var btn1 = $("#diyIntDef_" + treeNode.id);
        if (btn) btn.bind("blur", function () {
          treeNode.valuePath = btn.val();
        });
        if(treeNode.defaultValue == "") {
          treeNode.defaultValue = 0;
        }else{
          btn1.value = treeNode.defaultValue;
        }
        if (btn1) btn1.bind("click", function () {
          treeNode.defaultValue = btn1.val();
        });
      } else if (treeNode.name == 'isAudit') {
        var valuePath = "<input class='form-control'  value='" + treeNode.valuePath + "' "+
          "placeholder='路径:$.pollutant[0].Mark' id='diyIntPath_" + treeNode.id + "'>";
        aObj.after(valuePath);
        var defaultValue = "<select class='form-control'  value='" + treeNode.defaultValue + "' id='diyIntDef_" + treeNode.id + "'>" +
          "<option  value= 0 >否</option>" +
          "<option  value= 1 >是</option>" +
          " </select>";
        aObj.after(defaultValue);
        var btn = $("#diyIntPath_" + treeNode.id);
        var btn1 = $("#diyIntDef_" + treeNode.id);
        if (btn) btn.bind("blur", function () {
          treeNode.valuePath = btn.val();
        });
        if(treeNode.defaultValue == "") {
          treeNode.defaultValue = 0;
        }else{
          btn1.value = treeNode.defaultValue;
        }
        if (btn1) btn1.bind("click", function () {
          treeNode.defaultValue = btn1.val();
        });
      }  else if (treeNode.name == 'length') {
        var valuePath = "<input class='form-control'   value='" + treeNode.valuePath + "' " +
          "  placeholder='路径:$.pollutant[0].Mark'   id='diyIntPath_" + treeNode.id + "'>";
        aObj.after(valuePath);
        var defaultValue = "<input class='form-control' value='" + treeNode.defaultValue + "' " +
          " placeholder='默认值 '  type='number' id='diyIntDef_" + treeNode.id + "'>";
        aObj.after(defaultValue);
        var btn = $("#diyIntPath_" + treeNode.id);
        var btn1 = $("#diyIntDef_" + treeNode.id);
        if (btn) btn.bind("blur", function () {
          treeNode.valuePath = btn.val();
        });
        if (btn1) btn1.bind("blur", function () {
          treeNode.defaultValue = btn1.val();
        });
      } else {
        var valuePath = "<input class='form-control'   value='" + treeNode.valuePath + "' " +
          "  placeholder='路径:$.pollutant[0].Mark'   id='diyIntPath_" + treeNode.id + "'>";
        aObj.after(valuePath);
        var defaultValue = "<input class='form-control' value='" + treeNode.defaultValue + "' " +
          " placeholder='默认值 ' id='diyIntDef_" + treeNode.id + "'>";
        aObj.after(defaultValue);
        var btn = $("#diyIntPath_" + treeNode.id);
        var btn1 = $("#diyIntDef_" + treeNode.id);
        if (btn) btn.bind("blur", function () {
          treeNode.valuePath = btn.val();
        });
        if (btn1) btn1.bind("blur", function () {
          treeNode.defaultValue = btn1.val();
        });
      }
      // console.log(treeNode)
    }
  }

//添加隐藏Dom
  addHoverDom = (treeId, treeNode) => {
    if (treeNode.parentNode && treeNode.parentNode.id != 1) return;
    var aObj = $("#" + treeNode.tId + "_a");
    if (treeNode.nodeType == 1) {
      if ($("#diyBtn_" + treeNode.id).length > 0) return;
      if (treeNode.name == 'root') {
        if ($("#diyBtn_" + treeNode.id).length > 0) return;
        var addFieldBtn = "<span id='diyParent_" +treeNode.id+ "' >&nbsp;<span class='one-custom-icon one-custom-icon-F-add' id='diyBtn_" +treeNode.id+ "' title='添加字段'  ></span></span>"//<span class='one-custom-icon one-custom-icon-F-sec' id='diyBtn1_" +treeNode.id+ "' title='默认因子' ></span>
        aObj.append(addFieldBtn);
        var btn = $("#diyBtn_" + treeNode.id);
        var outThis = this;
        if (btn) btn.bind("click", function () {
          outThis.addFieldNode(treeNode);
        });
      } else if (treeNode.name == 'factors') {
        if ($("#diyBtn_" + treeNode.id).length > 0) return;
        if ($("#diyBtn1_" + treeNode.id).length > 0) return;
        if ($("#diyBtn2_" + treeNode.id).length > 0) return;
        var addDefaultFactor ="<span id='diyParent_" +treeNode.id+ "' >" +
          "<span class='one-custom-icon one-custom-icon-F-add' id='diyBtn_" +treeNode.id+ "' title='添加字段' ></span>" +
          "<span class='one-custom-icon one-custom-icon-F-sec' id='diyBtn1_" +treeNode.id+ "' title='默认因子'   onfocus='this.blur();'></span>" +
          "<span class='fa fa-clipboard' id='diyBtn2_" +treeNode.id+ "' title='粘贴因子'   onfocus='this.blur();'></span></span>"

        aObj.append(addDefaultFactor);
        var btn = $("#diyBtn_" + treeNode.id);
        var btn1 = $("#diyBtn1_" + treeNode.id);
        var btn2 = $("#diyBtn2_" + treeNode.id);

        var outThis = this;
        if (btn) btn.bind("click", function () {
          outThis.addFieldNode(treeNode);
        });
        if (btn1) btn1.bind("click", function () {
          outThis.addDefaultFactor(treeNode);
        });
        if (btn2) btn2.bind("click", function () {
          outThis.pasteNodes();
        });

      } else if (treeNode.getParentNode().name == 'factors') {
        var addAttrAndCopy ="<span id='diyParent_" +treeNode.id+ "' ></span>" +
          "<span class='one-custom-icon one-custom-icon-A-add' id='diyBtn_" +treeNode.id+ "' title='添加属性'   onfocus='this.blur();'></span>" +
          "<span class='fa fa-files-o' id='diyBtn1_" +treeNode.id+ "' title='复制因子'   onfocus='this.blur();' aria-hidden='true' ></span></span>";
        aObj.append(addAttrAndCopy);
        var btn = $("#diyBtn_" + treeNode.id);
        var btn1 = $("#diyBtn1_" + treeNode.id);
        var outThis = this;
        if (btn) btn.bind("click", function () {
          outThis.addAttributeNode(treeNode);
        });
        if (btn1) btn1.bind("click", function () {
          outThis.copyNodes();
        });
      }  else if(treeNode.nodeType == 1 && treeNode.getParentNode().name == 'root' && (!treeNode.children || treeNode.children[0].nodeType ==3)){
        if ($("#diyBtn_" + treeNode.id).length > 0) return;
        if ($("#diyBtn1_" + treeNode.id).length > 0) return;
        var addAttrBtn = "<span id='diyParent_" +treeNode.id+ "' >" +
          "<span class='one-custom-icon one-custom-icon-A-add' id='diyBtn_" +treeNode.id+ "' title='添加属性'   onfocus='this.blur();'></span>" +
          "<span class='one-custom-icon one-custom-icon-M-add' id='diyBtn1_" +treeNode.id+ "' title='添加元属性'   onfocus='this.blur();'></span></span>";
        aObj.append(addAttrBtn);
        var btn = $("#diyBtn_" + treeNode.id);
        var btn1 = $("#diyBtn1_" + treeNode.id);
        var outThis = this;
        if (btn) btn.bind("click", function () {
          outThis.addAttributeNode(treeNode);
        });
        if (btn1) btn1.bind("click", function () {
          outThis.addMetaAttributeInput();
        });
      }else {
        if ($("#diyBtn_" + treeNode.id).length > 0) return;
        var addAttrBtn = "<span id='diyParent_" +treeNode.id+ "' >" +
          "<span class='one-custom-icon one-custom-icon-M-add' id='diyBtn_" +treeNode.id+ "' title='添加属性'   onfocus='this.blur();'></span></span>";
        aObj.append(addAttrBtn);
        var btn = $("#diyBtn_" + treeNode.id);
        var outThis = this;
        if (btn) btn.bind("click", function () {
          outThis.addAttributeNode(treeNode);
        });
      }
    } else if (treeNode.nodeType == 2) {
      if ($("#diyBtn_" + treeNode.id).length > 0) return;
      if ($("#diyBtn1_" + treeNode.id).length > 0) return;
      // var addMetaAttrBtn = "<ul id='diyParent_" + treeNode.id + "' style='display: inline-block;' class='list-inline'><li><button class='btn btn-default' id='diyBtn_" + treeNode.id + "'>添加元属性</button></li>" +
      //   "<li><button class='btn btn-default' id='diyBtn1_" + treeNode.id + "' >默认元属性</button></li></ul>";
      var addMetaAttrBtn ="<span id='diyParent_" +treeNode.id+ "' >" +
        "<span class='one-custom-icon one-custom-icon-M-sec' id='diyBtn1_" +treeNode.id+ "' title='默认元属性'   onfocus='this.blur();'></span>" +
        "<span class='one-custom-icon one-custom-icon-M-add' id='diyBtn_" +treeNode.id+ "' title='添加元属性'   onfocus='this.blur();'></span></span>";
      aObj.append(addMetaAttrBtn);
      var btn = $("#diyBtn_" + treeNode.id);
      var btn1 = $("#diyBtn1_" + treeNode.id);
      var outThis = this;
      // this.selectedNode = this.treeObj.selectNode(treeNode,false)
      if (btn) btn.bind("click", function () {
        outThis.addMetaAttributeInput(treeNode);
      });
      if (btn1) btn1.click(function () {
        outThis.addDefaultMetaAttr(treeNode)
      });
    }

  }


  private removeHoverDom(treeId, treeNode) {

    if (treeNode.nodeType != 3) {
      $("#diyBtn_" + treeNode.id).unbind().remove();
      $("#diyBtn1_" + treeNode.id).unbind().remove();
      $("#diyBtn2_" + treeNode.id).unbind().remove();
      $("#diyParent_" + treeNode.id).remove();
    }

  };

  /**
   * 添加元属性节点
   */
  addMetaAttributeInput(treeNode?: any) {
    var treeObj = $.fn.zTree.getZTreeObj("field_add_fieldConfTree");
    var nodes = treeNode ? [treeNode]: treeObj.getSelectedNodes();
    if (nodes.length == 0) {
      this.dialogService.modalInfo("请选择一个节点");
    } else if (nodes[0].nodeType == 3) {
      this.dialogService.modalInfo("当前节点为属性节点，请重新选择");
    } else if (nodes[0].nodeType == 2) {
      var newNode = {
        id: this.getUUID(), nodeType: 3, name: this.metaAttribute + metaAttributeNumber++, icon: 'assets/v1/css/audit/imgs/M.svg'
      };
       this.treeObj.addNodes(nodes[0], newNode);
    } else if (nodes[0].nodeType == 1 && nodes[0].getParentNode().name == 'root' && (!nodes[0].children || nodes[0].children[0].nodeType ==3)) {
      nodes[0].nodeType = 2;
      nodes[0].icon='assets/v1/css/audit/imgs/A.svg'
      this.treeObj.updateNode(nodes[0]);
      var newNode = {
        id: this.getUUID(), nodeType: 3, name: this.metaAttribute + metaAttributeNumber++, icon: 'assets/v1/css/audit/imgs/M.svg'
      };
      this.treeObj.addNodes(nodes[0], newNode);
    }else{
      this.dialogService.modalInfo("当前节点下有属性节点，无法添加元属性");
    }
  }

  /**
   * 添加默认元属性
   */
  addDefaultMetaAttr(treeNode?: any) {
    var treeObj = $.fn.zTree.getZTreeObj("field_add_fieldConfTree");
    var nodes = treeNode ? [treeNode] :  treeObj.getSelectedNodes();
    if (nodes.length == 0) {
      this.dialogService.modalInfo("请选择一个节点");
    } else if (nodes[0].nodeType == 3) {
      this.dialogService.modalInfo("当前节点为属性节点，请重新选择");
    } else if (nodes[0].nodeType == 2) {
      var node = nodes[0];
      if (node.children && node.children.length >= 7) {
        this.dialogService.modalInfo("当前节点已经存在默认元属性，无需添加");
      } else {
        var newNodes = [
          {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
          {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
          {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
          {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
          {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
          {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
          {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
        ];
         this.treeObj.addNodes(node, newNodes);
      }
    }
  }

  /**
   * 添加属性
   */
  addAttributeNode(treeNode?: any) {
    var treeObj = $.fn.zTree.getZTreeObj("field_add_fieldConfTree");
    var nodes = treeNode ? [treeNode] :  treeObj.getSelectedNodes();
    if (nodes.length == 0) {
      this.dialogService.modalInfo("请选择一个节点");
    } else if (nodes[0].nodeType == 3) {
      this.dialogService.modalInfo("当前节点为属性节点，请重新选择");
    } else if (nodes[0].nodeType == 2) {
      this.dialogService.modalInfo("当前节点下有属性节点，新增属性请选择添加属性");
    } else if (nodes[0].nodeType == 1) {
      var newNode = {id: this.getUUID(), nodeType: 2, name: this.attribute + attributeNumber++,  icon: 'assets/v1/css/audit/imgs/A.svg'};
      this.treeObj.addNodes(nodes[0], newNode);
    }
  }

  /**
   * 添加字段
   */
  addFieldNode(treeNode?: any) {
    var treeObj = $.fn.zTree.getZTreeObj("field_add_fieldConfTree");
    var nodes = treeNode ? [treeNode] :  treeObj.getSelectedNodes();
    var node = nodes[0];
    if (nodes.length == 0) {
      this.dialogService.modalInfo("请选择一个节点");
    } else if (node.nodeType == 3) {
      this.dialogService.modalInfo("当前节点为属性节点，请重新选择");
    } else if (node.nodeType == 2) {
      this.dialogService.modalInfo("当前节点下有属性节点，新增属性请选择添加属性");
    } else if (node.nodeType == 1) {
      if (node.name == 'root' || node.name == 'factors') {
        //维护格式统一，只允许在根节点下和factors下新增  node.getParentNode().name == 'root'
        if (node.name == 'root') {
          var newNode = {id: this.getUUID(), nodeType: 1, name: this.name + (nameNumber++), icon: 'assets/v1/css/audit/imgs/F.svg'};
        } else {
          var newNode = {id: this.getUUID(), nodeType: 1, name: this.factor + (factorNumber++), icon: 'assets/v1/css/audit/imgs/F.svg'};
        }
      } else {
        this.dialogService.modalInfo("请在 root 或者 factors 下添加字段");
      }
      this.treeObj.addNodes(node, newNode);
    }
  }

  //添加默认因子
  addDefaultFactor(treeNode?: any ) {
    var treeObj = $.fn.zTree.getZTreeObj("field_add_fieldConfTree");
    var nodes = treeNode ? [treeNode] :  treeObj.getSelectedNodes();
    var node = nodes[0];
    if (node.nodeType == 1 && node.name == 'factors') {
      var factorNode = {
        id: this.getUUID(),
        nodeType: 1,
        name: this.factor + (factorNumber++),
        open: true,
        children: [
          {
            id: this.getUUID(), nodeType: 2, name: "code", open: true, icon: 'assets/v1/css/audit/imgs/A.svg',
            children: [
              {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
            ]
          },
          {
            id: this.getUUID(), nodeType: 2, name: "name", open: true, icon: 'assets/v1/css/audit/imgs/A.svg',
            children: [
              {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
            ]
          },
          {
            id: this.getUUID(), nodeType: 2, name: "value", open: true, icon: 'assets/v1/css/audit/imgs/A.svg',
            children: [
              {id: this.getUUID(), nodeType: 3, name: "code", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "name", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "type", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "value", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "length", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isAudit", icon: 'assets/v1/css/audit/imgs/M.svg'},
              {id: this.getUUID(), nodeType: 3, name: "isVisiable", icon: 'assets/v1/css/audit/imgs/M.svg'},
            ]
          },
        ]
      }
       this.treeObj.addNodes(node, factorNode);
    } else {
      this.dialogService.modalInfo("请在 factors 下添加因子")
    }
  }

  /**
   * 删除节点
   */
  removeField() {
    // console.log("fieldConfs结构数据" + JSON.stringify(this.fieldConfs));
    this.dialogService.modalInfoWithCancelBtn("确定重置？", this.confirmRemove);
  }

  confirmRemove = () => {
    this.treeObj.destroy();
    this.treeObj = $.fn.zTree.init($("#field_add_fieldConfTree"), this.setting, this.zNodes);

  }

  /**
   * 展开折叠节点
   */
  expandAll(){
    if(this.expand == true){
      this.expand = false;
    }else {
      this.expand = true;
    }
    this.treeObj.expandAll(this.expand)
  }

  //复制节点
  copyNodes() {
    this.saveCopyNodes = [];
    this.saveCopyNodes = this.treeObj.getSelectedNodes();
  }

  //粘贴节点
  pasteNodes() {
    if (this.saveCopyNodes && this.saveCopyNodes.length != 0) {
      var nodes = this.treeObj.getSelectedNodes();
      var node = nodes[0];
      if (node.name = 'factors') {
        this.treeObj.addNodes(node, this.saveCopyNodes)
      } else {
        this.dialogService.modalInfo("请在 factors 下粘贴因子")
      }
    } else {
      this.dialogService.modalInfo("请先复制节点")
    }
  }

  /**
   * 提交
   */
  onSubmit() {
    var ZTreeNodes = this.treeObj.getNodes();
    this.jsonTransformPo(ZTreeNodes);
    var fieldConfs = JSON.stringify(this.fieldConfs)
    // 获取表单信息
    this.dsConf = this.fieldConfForm.value;
    this.dsConfService.insertDsConf(this.dsConf, fieldConfs).subscribe(
      result => this.responseUtil.success(result, this.processFieldInsertResult),
      message => this.responseUtil.error(message)
    );
  }

  private processFieldInsertResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      // this.dialogService.success(result.message, () => this.cancelFieldAdd());
      this.dialogService.successWithCancelBtn('添加成功，是否继续添加？', () => this.initObject(), () => this.cancelFieldConfAdd());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消
   */
  cancelFieldConfAdd() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 为每个节点添加pId 和code
   * 将json转换为List<po>
   *
   */
  jsonTransformPo(zNodes) {
    for (var i = 0; i < zNodes.length; i++) {
      zNodes[i].id = this.getUUID();
      zNodes[i].code = 1;
      this.nodeTransformPo(zNodes[i]);
      for (var j = 0; j < zNodes[i].children.length; j++) {
        zNodes[i].children[j].id = this.getUUID();
        zNodes[i].children[j].pId = zNodes[i].id;
        zNodes[i].children[j].code = (100 + j);
        this.nodeTransformPo(zNodes[i].children[j]);
        for (var k = 0; k < zNodes[i].children[j].children.length; k++) {
          zNodes[i].children[j].children[k].id = this.getUUID();
          zNodes[i].children[j].children[k].pId = zNodes[i].children[j].id;
          zNodes[i].children[j].children[k].code = (100 + j) * 1000 + 100 + k;
          this.nodeTransformPo(zNodes[i].children[j].children[k]);
          if (zNodes[i].children[j].children[k].children && zNodes[i].children[j].children[k].children.length != 0) {
            for (var l = 0; l < zNodes[i].children[j].children[k].children.length; l++) {
              zNodes[i].children[j].children[k].children[l].id = this.getUUID();
              zNodes[i].children[j].children[k].children[l].pId = zNodes[i].children[j].children[k].id;
              zNodes[i].children[j].children[k].children[l].code = (100 + j) * 1000000 + (100 + k) * 1000 + 100 + l;
              this.nodeTransformPo(zNodes[i].children[j].children[k].children[l]);
              if (zNodes[i].children[j].children[k].children[l].children && zNodes[i].children[j].children[k].children[l].children.length != 0) {
                for (var m = 0; m < zNodes[i].children[j].children[k].children[l].children.length; m++) {
                  zNodes[i].children[j].children[k].children[l].children[m].id = this.getUUID();
                  zNodes[i].children[j].children[k].children[l].children[m].pId = zNodes[i].children[j].children[k].children[l].id;
                  zNodes[i].children[j].children[k].children[l].children[m].code = (100 + j) * 1000000000 + (100 + k) * 1000000 + (100 + l) * 1000 + 100 + m;
                  this.nodeTransformPo(zNodes[i].children[j].children[k].children[l].children[m]);
                }
              }
            }
          }
        }
      }
    }
  }


  // recursionGetChildren(zNodes) {
  //   // for (var j = 0; j < zNodes.length; j++) {
  //     // zNodes[j].pid = zNodes
  //     // this.nodeTransformPo(zNodes[j]);
  //     if (zNodes.getChildren  != 0) {
  //       for (var i = 0; i < zNodes.getChildren; i++) {
  //         zNodes[0].children[i].pid = zNodes[0].id;
  //         zNodes[0].children[i].code = (zNodes[0].code * 1000) + 100 + i;
  //         this.nodeTransformPo(zNodes[0].children[i]);
  //         if (zNodes[0].children[i].children && zNodes[0].children[i].children.length != 0) {
  //           this.recursionGetChildren(zNodes[0].children[i]);
  //         }
  //       }
  //     }
  //   // }
  // }


  nodeTransformPo(node) {
    var fieldconf = new Fieldconf();
    fieldconf.id = node.id;
    fieldconf.pId = node.pId;
    // fieldconf.dsConfId = node.dsConfId;
    fieldconf.code = node.code;
    fieldconf.nodeType = node.nodeType;
    fieldconf.name = node.name;
    fieldconf.valuePath = node.valuePath;
    fieldconf.defaultValue = node.defaultValue;
    this.fieldConfs.push(fieldconf)
  }

  /**
   * 实例化对象
   */
  initObject() {
    this.fieldConf = new Fieldconf();
    this.dsConf = new Dsconf('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
    this.buildForm();
  }

  /**
   * 获取32位UUID
   * @returns {string}
   */

  getUUID() {
    var len = 32;
    var radix = 36;
    var chars = CHARS, uuid = [], i;
    radix = radix || chars.length;

    if (len) {
      // Compact form
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      // rfc4122, version 4 form
      var r;

      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return uuid.join('');
  };


  /**
   * 初始化数据源和表格
   */
  private initDsConfNameAndTable() {
    this.dsService.getDataSourceInfos().subscribe(
      result => this.responseUtil.success(result, this.generateDsInfos),
      message => this.responseUtil.error(message)
    );
  }

  private generateDsInfos = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        result.data.forEach((val) => {
          if(val.isUse == '1') {
            this.auditDsIdNames.push({
              name: val.dsName,
              value: val.id
            })
          }
        })
        result.data.forEach((val) => {
          if(val.isUse == '1') {
            this.oriDsNames.push({
              name: val.dsName,
              value: val.id
            })
          }
        })
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 选择数据源后初始化表
   * @param {String} dsType
   */
  changeSelect(dsType: String) {

    if (dsType == 'ori') {
      this.oriTables = [];
      // const oriDs = elem.target.value;
      // this.fieldConfForm.value.oriDsId=this.fieldConfForm.value.oriDsName.value
      const oriDs = this.fieldConfForm.value.oriDsId;
      if (oriDs != '' && oriDs != null) {
        this.getOriTableByDsId(oriDs);
      } else {
        this.dialogService.modalInfo("请选择数据源后点击")
      }
    }
    if (dsType == 'audit') {
      this.auditTables = [];
      // const auditDs = this.dsConfForm.value.auditDsId; //无效
      const auditDs = this.fieldConfForm.value.auditDsId;
      if (auditDs != '' && auditDs != null) {
        this.getAuditTableByDsId(auditDs);
      } else {
        this.dialogService.modalInfo("请选择数据源后点击")
      }
    }
  }

  changeOriId(oriTable) {
    this.fieldConfForm.patchValue({oriTable: oriTable});
  }
  changeAuditId(oriTable) {
    this.fieldConfForm.patchValue({auditTable: oriTable});
  }

  /**
   * 获取原始表
   * @param {Dsconf} dsConf
   */
  getOriTableByDsId(dsId) {
    this.dsConfService.getTableByDsId(dsId).subscribe(
      result => this.responseUtil.success(result, this.generateOriTableByDsId),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 获取原始表后处理
   * @param {MsgResult} result
   */
  private generateOriTableByDsId = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      result.data.forEach((val) => {
        this.oriTables.push({
          name: val,
          // value: val.id
        })
      })
      // this.oriTables = result.data.oriTable;
      // this.dsConfForm.patchValue(this.dsConf);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 获取存储表
   * @param {Dsconf} dsConf
   */
  getAuditTableByDsId(auditDsId) {
    this.dsConfService.getTableByDsId(auditDsId).subscribe(
      result => this.responseUtil.success(result, this.generateAuditTableByDsId),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 获取存储表后处理
   * @param {MsgResult} result
   */
  private generateAuditTableByDsId = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {

      // this.dsConf.auditDsIdName = result.data.auditDsIdName;
      result.data.forEach((val) => {
        this.auditTables.push({
          name: val,
          // value: val.id
        })
      })
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //选择移除
  showRemoveBtn(treeId, treeNode) {
    var names: Array<string> = ['name', 'code', 'value', 'isAudit', 'isVisiable', 'root', 'site', 'device', 'factors', 'type', 'length'];
    var isExists: boolean = true;
    for (var i = 0; i < names.length; i++) {
      if (treeNode.name == names[i]) {
        isExists = false;
      }
    }
    return isExists;
  }

  //选择修改名称
  showRenameBtn(treeId, treeNode) {
    var names: Array<string> = ['name', 'code', 'value', 'isAudit', 'isVisiable', 'root', 'site', 'device', 'factors', 'type', 'length'];
    var isExists: boolean = true;
    for (var i = 0; i < names.length; i++) {
      if (treeNode.name == names[i]) {
        isExists = false;
      }
    }
    return isExists;
  }



  beforeRename(treeId, treeNode, newName, isCancel) {
    className = (className === "dark" ? "":"dark");
    if (newName.length == 0) {
      setTimeout(function() {
        var zTree = $.fn.zTree.getZTreeObj("field_add_fieldConfTree");
        zTree.cancelEditName();
        this.dialogService.modalInfo("节点名称不能为空");

      }, 0);
      return false;
    }
    return true;
  }



}
